//接口的基地址
axios.defaults.baseURL = "https://hmajax.itheima.net"

//轻提示框函数
function toastShow(msg){
    const toast = document.querySelector(".my-toast")
    const myToast = new bootstrap.Toast(toast)
    document.querySelector(".toast-body").innerHTML = msg

    myToast.show()
}
// toastShow("注册成功")


//抽取函数校验token
function checkLogin(){
    const token = localStorage.getItem("token")
    if(token === null){
        toastShow("请先登录")
        setTimeout(() => {
            location.href = "./login.html"
        }, 1500);
    }
}

//抽取函数渲染用户名
function getUsername(){
    const username = localStorage.getItem("username")

    document.querySelector(".username").innerHTML = username
}


//抽取函数点击退出
function logout(){
    const quit = document.querySelector("#logout")
    quit.addEventListener("click",function(){
        location.href = "./login.html"
        localStorage.removeItem("username")
        localStorage.removeItem("token")
    })
}

//添加请求拦截器  
axios.interceptors.request.use(function(config){
    //获取token
    const token = localStorage.getItem("token")
    
    //如果获取到的token不为空,将token存储在请求头中
    if(token){
        config.headers.Authorization = token
    }
    
    //以上都是在发送请求数据之前的动作
    return config
},function(error){
    return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {

    // 对响应数据做点什么
    return response.data;
  }, function (error) {

    if(error.response.status == 401){
        toastShow("登录失败,请重新登录")
        localStorage.removeItem("username")
        localStorage.removeItem("token")
        setTimeout(() => {
            location.href = "./login.html"
        }, 1500);
    }
    // 对响应错误做点什么
    return Promise.reject(error);
  }); 
